package com.pacifictextiles.qc.inspection.server.controller.servlets;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthAdminSVL extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private String adminPasswd = null;

	public AuthAdminSVL() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");

		// 得到文件路径
		String path = getServletContext().getRealPath("/admin.txt");

		// 设置管理员密码
		setAdminPasswd(readPassword(path));

		// 获取请求参数
		String passwd = request.getParameter("passwd");

		PrintWriter out = response.getWriter();

		// 验证密码 如果没有参数传入，也是return false
		if (passwd != null && passwd.equals(this.adminPasswd)) {
			out.write("true");
			out.flush();
		} else {
			out.write("false");
			out.flush();
		}
		out.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private String readPassword(String path) {

		String adminPasswd = null;

		String line = null;

		try {

			// 读取文件 要读取整行必须使用外接reader 直接使用file reader 无法读取
			// 新建一个reader
			BufferedReader filereader = new BufferedReader(new FileReader(path));

			line = filereader.readLine();

			if (line != null) {
				adminPasswd = line;
			}

			// System.out.print("the password is "+adminPasswd+"\n");
			filereader.close();

		} catch (FileNotFoundException e) {
			System.out.print("Admin set password:  找不到该文件" + "\n");
		} catch (IOException e) {
			System.out.print("Admin set password:  输出错误" + "\n");
		}
		return adminPasswd;
	}

	public void setAdminPasswd(String adminPasswd) {
		this.adminPasswd = adminPasswd;
	}

	public String getAdminPasswd() {
		return this.adminPasswd;
	}
}
